'use strict';

const uniID = require('uni-id-common');
const db = uniCloud.database();
const users = db.collection('uni-id-users'); // 可根据你的实际用户表修改

exports.main = async (event, context) => {
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
  const { uniIdToken, fields } = body;
  console.log(body)
  if (!uniIdToken || !Array.isArray(fields)) {
    return {
      code: 400,
      msg: '参数错误：缺少 uniIdToken 或 fields'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  const { uid, errCode, message } = await uniIDIns.checkToken(uniIdToken);
  if (!uid) {
    return {
      code: 401,
      msg: message || 'Token 校验失败',
      errCode
    };
  }

  try {
    const fieldObj = {};
    fields.forEach(field => {
      fieldObj[field] = true;
    });

    const userRes = await users.doc(uid).field(fieldObj).get();

    if (userRes.data && userRes.data.length > 0) {
      return {
        code: 200,
        data: userRes.data[0]
      };
    } else {
      return {
        code: 404,
        msg: '用户不存在'
      };
    }
  } catch (e) {
    return {
      code: 500,
      msg: '查询出错',
      error: e.message
    };
  }
};
